package cn.bluech.lib.utils;

import android.os.Handler;
import android.os.Looper;

import java.util.Timer;
import java.util.TimerTask;

/**
 * App长时间在后台/息屏时Timer会被暂停，亮屏后会一起执行，将导致堵死主线程
 */
public class TimeCounter {
    private Timer timer;
    private Handler handler;
    private long startTime;
    private long lastRunTime;
    private boolean isStarted;

    private Listener listener;

    public TimeCounter(){
        timer = new Timer();
        handler = new Handler(Looper.getMainLooper());
        startTime = -1;
    }

    public long getStartTime() {
        return startTime;
    }

    public boolean start(int delay, int period, Listener listener){
        synchronized (this){
            if(isStarted)
                return false;
            isStarted = true;
        }

        this.listener = listener;
        startTime = System.currentTimeMillis();
        lastRunTime = -1;
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                long curTime = System.currentTimeMillis();
                if (lastRunTime+period>curTime){
                    return;
                }
                lastRunTime = curTime;

                handler.post(() -> {
                    final Listener lis = TimeCounter.this.listener;
                    if(null!=lis)
                        lis.onTimeCount(TimeCounter.this,System.currentTimeMillis()-startTime);
                });
            }
        },delay,period);

        return true;
    }

    public void release(){
        synchronized (this) {
            isStarted = true;
        }
        if(null!=timer) {
            timer.cancel();
            timer = null;
        }
        listener = null;
    }

    public interface Listener{
        void onTimeCount(TimeCounter counter, long timeTotal);
    }
}
